import os
import yaml
import subprocess

from flask import Flask, make_response, request, send_file, abort

app = Flask(__name__)


auth_token = ''


@app.route('/sync_files', methods=['GET'])
def get_token():
    param_token = request.args.get("token")
    if not param_token or param_token != auth_token:
        print(param_token, auth_token)
        return make_response(str("illegal request!").encode('utf-8'), 401)

    try:
        print("get files form shore server.")
        cmd = "find /var/soms -mtime +1"
        result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        files = result.communicate()
        file_list, error_msg = files[0], files[1]
        file_list = str(file_list, encoding='utf-8')
        error_msg = str(error_msg, encoding='utf-8')
        return make_response(file_list.encode('utf-8'), 200)
    except Exception as e:
        print(e)
        return make_response(str(error_msg + str(e)).encode('utf-8'), 500)


@app.route('/download', methods=['GET'])
def download():
    param_token = request.args.get("token")
    if not param_token or param_token != auth_token:
        return make_response(str("illegal request!").encode('utf-8'), 401)
    file_path = request.args.get("file_path")
    if os.path.isfile(file_path):
        return send_file(file_path, as_attachment=True)
    return make_response("{} not found.".format(file_path).encode('utf-8'), 404)


if __name__ == '__main__':
    with open("/opt/sync/config.yaml", "r") as file:
        sync_config = file.read()
        sync_config_yaml = yaml.safe_load(sync_config)

        auth_token = sync_config_yaml['auth']['token']
        if not auth_token:
            print("Error: auth_token is not set.")
            exit(500)
    print("starting sync_files.py")
    app.run(host='0.0.0.0', port=18000)
